import sys
import os

file_path = os.path.abspath(__file__)
end = file_path.index('qmt_auto_trade') + 17
project_path = file_path[0:end]
sys.path.append(project_path)


from mk_common.component.db.SQLiteManager import SQLiteManager

import config.config_service as config_service
import mk_common.util.data_frame_util as data_frame_util


# 查询当天是否买入过
def query_today_trade(symbol, str_day):
    config_info_dict = config_service.get_config_info()
    trader_db_name = config_info_dict.get('trader_db_name')

    with SQLiteManager(trader_db_name) as db:
        trade_table_name = config_info_dict.get('stock_trade_record')
        query = f"""
    SELECT * 
    FROM {trade_table_name} AS t
    WHERE t.str_day = '{str_day}' 
      AND t.symbol = '{symbol}'
"""
        df = db.query_to_dataframe(query)
        if data_frame_util.is_empty(df):
            return False
        else:
            return True


def insert_trade_data(now_date, symbol,
                      operate_code, trade_price,
                      trade_volume,  trade_number ):
    str_day = now_date.strftime('%Y-%m-%d')
    id_key = symbol + '_' + str_day + '_' + operate_code
    str_now_time = now_date.strftime('%Y-%m-%d %H:%M:%S')
    config_info_dict = config_service.get_config_info()
    trader_db_name = config_info_dict.get('trader_db_name')
    stock_trade_record = config_info_dict.get('stock_trade_record')
    with SQLiteManager(trader_db_name) as sq_lite_db:
        trade_data = {
            'id': id_key,
            'symbol': symbol,
            'str_day': str_day,
            'trade_price': trade_price,
            'trade_money': round(trade_price * trade_volume, 2),
            'trade_volume': trade_volume,
            'trade_number': trade_number,
            'str_now_time': str_now_time,
            'trade_type': operate_code,

        }
        sq_lite_db.insert_record(stock_trade_record,
                                 trade_data)


def insert_self_position(table_name,position_df):
    config_info_dict = config_service.get_config_info()
    trader_db_name = config_info_dict.get('trader_db_name')
    with SQLiteManager(trader_db_name) as sq_lite_db:
        sq_lite_db.insert_dataframe(table_name,
                                    position_df)

